import axios from 'axios'
import Vue from 'vue'
import {
	Message
} from 'element-ui' // 引入Loading,MessageBox
import store from '@/store'
import {
	getToken
} from '@/utils/auth'


// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 120000 // request timeout
})

let loading = 0
const startLoading = () => {
	loading = Vue.prototype.$loading({
		lock: false,
		background: 'rgba(0, 0, 0, 0.3)',
		text: '正在加载',
		spinner: 'el-icon-loading',
	})
}
const endLoading = () => {
	if (loading) {
		loading.close()
	}
}

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		let isloading = typeof(config.loading) == 'undefined' ? true : config.loading;
		if (isloading) {
			startLoading();
		}
		if (store.getters.token) {
			config.headers['user-token'] = getToken()
		}

		if (config.method === 'post') {
			config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
			if (config.upFile) {
				config.headers['Content-Type'] = 'multipart/form-data' //文件上传请求格式
			}
		} else {
			config.headers['Content-Type'] = 'application/json;charset=utf-8'
		}
		if (config.timeout) {
			config.timeout = config.timeout
		}
		return config
	},
	error => {
		endLoading()
		// do something with request error
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		let isloading = typeof(response.config.loading) == 'undefined' ? true : response.config.loading;
		if (isloading) { 
			endLoading(); 
		}
		const res = response.data;
		if (res.data === 101 || res.data === 102) {
			store.dispatch('user/resetToken').then(() => {
				location.reload()
			})
		} else {
			return res
		}
	},
	error => {
		endLoading();
		// console.log('err' + error) // for debug
		Message({
			message: '服务器开小差了',
			type: 'error',
			duration: 5 * 1000
		})
		// return Promise.reject(error)
	}
)

export default service
